<template>
  <el-dialog
    :title="$t('project.createAnnouncement')"
    v-model="dialogVisible"
    width="700px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      v-loading="loading"
    >
      <!-- 公告标题 -->
      <el-form-item :label="$t('project.announcementTitle')" prop="title">
        <el-input 
          v-model="form.title" 
          :placeholder="$t('project.announcementTitlePlaceholder')"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 公告内容 -->
      <el-form-item :label="$t('project.announcementContent')" prop="content">
        <div class="editor-container">
          <div class="editor-tabs">
            <div 
              class="tab-item" 
              :class="{ active: editorTab === 'write' }"
              @click="editorTab = 'write'"
            >
              {{ $t('project.write') }}
            </div>
            <div 
              class="tab-item" 
              :class="{ active: editorTab === 'preview' }"
              @click="editorTab = 'preview'"
            >
              {{ $t('project.preview') }}
            </div>
          </div>
          <div class="editor-content">
            <el-input 
              v-if="editorTab === 'write'"
              v-model="form.content" 
              type="textarea" 
              :rows="10"
              :placeholder="$t('project.announcementContentPlaceholder')"
              maxlength="10000"
              show-word-limit
            />
            <div 
              v-else
              class="preview-content"
              v-html="previewContent"
            ></div>
          </div>
          <div class="editor-footer">
            <div class="markdown-hint">
              {{ $t('project.markdownSupported') }}
              <el-link 
                type="primary" 
                href="https://www.markdownguide.org/basic-syntax/" 
                target="_blank"
              >
                {{ $t('project.markdownGuide') }}
              </el-link>
            </div>
          </div>
        </div>
      </el-form-item>

      <!-- 置顶选项 -->
      <el-form-item>
        <el-checkbox v-model="form.isPinned">
          {{ $t('project.pinAnnouncement') }}
        </el-checkbox>
        <div class="checkbox-hint">
          {{ $t('project.pinAnnouncementHint') }}
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ $t('common.publish') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { announcementApi } from '@/api/project'
import type { AnnouncementCreateRequest } from '@/types/project'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

// Props
interface Props {
  modelValue: boolean
  projectId: number | null
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

const { t } = useI18n()

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const editorTab = ref<'write' | 'preview'>('write')
const form = ref<AnnouncementCreateRequest>({
  projectId: props.projectId || 0,
  title: '',
  content: '',
  isPinned: false
})

// 计算属性
const previewContent = computed(() => {
  if (!form.value.content) {
    return '<div class="empty-preview">' + t('project.noContentToPreview') + '</div>'
  }
  
  try {
    const html = marked(form.value.content)
    return DOMPurify.sanitize(html)
  } catch (error) {
    console.error('Markdown解析错误:', error)
    return form.value.content
  }
})

// 表单验证规则
const rules = computed<FormRules>(() => ({
  title: [
    { required: true, message: t('project.announcementTitleRequired'), trigger: 'blur' },
    { min: 2, max: 200, message: t('project.announcementTitleLength'), trigger: 'blur' }
  ],
  content: [
    { required: true, message: t('project.announcementContentRequired'), trigger: 'blur' },
    { min: 10, message: t('project.announcementContentMinLength'), trigger: 'blur' }
  ]
}))

// 方法
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  formRef.value?.resetFields()
  form.value = {
    projectId: props.projectId || 0,
    title: '',
    content: '',
    isPinned: false
  }
  editorTab.value = 'write'
}

const handleSubmit = async () => {
  if (!formRef.value || !props.projectId) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.value = true
      
      // 格式化数据
      const formData = {
        ...form.value,
        projectId: props.projectId!
      }
      
      await announcementApi.createAnnouncement(formData)
      
      ElMessage.success(t('project.createAnnouncementSuccess'))
      emit('success')
      handleClose()
    } catch (error) {
      console.error('创建公告失败:', error)
      ElMessage.error(t('project.createAnnouncementError'))
    } finally {
      loading.value = false
    }
  })
}

// 监听projectId变化
watch(() => props.projectId, (newId) => {
  if (newId) {
    form.value.projectId = newId
  }
})
</script>

<style scoped lang="scss">
.editor-container {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  overflow: hidden;

  .editor-tabs {
    display: flex;
    border-bottom: 1px solid var(--el-border-color);
    background-color: var(--el-bg-color-page);

    .tab-item {
      padding: 12px 16px;
      cursor: pointer;
      font-size: 14px;
      color: var(--el-text-color-regular);
      transition: all 0.3s ease;

      &:hover {
        color: var(--el-color-primary);
      }

      &.active {
        color: var(--el-color-primary);
        font-weight: 500;
        border-bottom: 2px solid var(--el-color-primary);
      }
    }
  }

  .editor-content {
    min-height: 200px;

    .preview-content {
      padding: 16px;
      min-height: 200px;
      font-size: 14px;
      line-height: 1.6;
      color: var(--el-text-color-regular);

      .empty-preview {
        color: var(--el-text-color-placeholder);
        font-style: italic;
        text-align: center;
        padding: 40px 0;
      }

      :deep(p) {
        margin: 0 0 12px 0;
      }

      :deep(ul), :deep(ol) {
        margin: 0 0 12px 0;
        padding-left: 24px;
      }

      :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
        margin: 16px 0 8px 0;
        font-weight: 600;
        line-height: 1.4;
      }

      :deep(h1) {
        font-size: 20px;
      }

      :deep(h2) {
        font-size: 18px;
      }

      :deep(h3) {
        font-size: 16px;
      }

      :deep(h4), :deep(h5), :deep(h6) {
        font-size: 14px;
      }

      :deep(blockquote) {
        margin: 0 0 12px 0;
        padding: 8px 16px;
        border-left: 4px solid var(--el-border-color);
        background-color: var(--el-bg-color-page);
      }

      :deep(code) {
        padding: 2px 4px;
        background-color: var(--el-bg-color-page);
        border-radius: 4px;
        font-family: monospace;
      }

      :deep(pre) {
        margin: 0 0 12px 0;
        padding: 12px;
        background-color: var(--el-bg-color-page);
        border-radius: 4px;
        overflow-x: auto;

        code {
          padding: 0;
          background-color: transparent;
        }
      }

      :deep(a) {
        color: var(--el-color-primary);
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }

      :deep(img) {
        max-width: 100%;
        height: auto;
        border-radius: 4px;
      }

      :deep(table) {
        width: 100%;
        border-collapse: collapse;
        margin: 0 0 12px 0;

        th, td {
          padding: 8px;
          border: 1px solid var(--el-border-color);
          text-align: left;
        }

        th {
          background-color: var(--el-bg-color-page);
          font-weight: 600;
        }
      }
    }
  }

  .editor-footer {
    padding: 8px 16px;
    border-top: 1px solid var(--el-border-color);
    background-color: var(--el-bg-color-page);

    .markdown-hint {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}

.checkbox-hint {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
